#include "Magnetic.h"

#include <sensrvmagneticnorthsensor.h>
#include <sensrvchannelinfo.h>
#include <sensrvchannelfinder.h>
#include <sensrvpropertylistener.h>
#include <sensrvmagnetometersensor.h>


CSensorFinder* CSensorFinder::NewL(MMagneticReader& aReader)
{    
    CSensorFinder* self = new (ELeave) CSensorFinder( aReader );
	CleanupStack::PushL( self );
	self->ConstructL();    
	CleanupStack::Pop( self );
	return self;    
}

void  CSensorFinder::ConstructL()
{	
	CSensrvChannelFinder* channelFinder = CSensrvChannelFinder::NewL();    
    
	CleanupStack::PushL( channelFinder );
    RSensrvChannelInfoList channelInfoList;
    TSensrvChannelInfo channelInfo;

    channelInfo.iChannelType = KSensrvChannelTypeIdMagneticNorthData;
    channelFinder->FindChannelsL( channelInfoList, channelInfo );
    
    for( TInt i = 0; i< channelInfoList.Count(); i++ )
    {
        channelInfo = channelInfoList[i];
        if( channelInfo.iChannelType == KSensrvChannelTypeIdMagneticNorthData )
        {        
            iMagneticNorthSensor = CSensrvChannel::NewL( channelInfoList[ i ] );
            iMagneticNorthSensor->OpenChannelL();
            iMagneticNorthSensor->StartDataListeningL( this,1,1,0 );            
        }    
    }	
	
    CleanupStack::Pop(channelFinder);
    delete channelFinder, channelFinder = NULL;	
}

CSensorFinder::CSensorFinder( MMagneticReader& aReader ): iDataObserver( aReader )
{   
    iMagnetometerCalibrationLevel = 0;
    iMagnetometerAngleFromNorth = 0;    
}

CSensorFinder::~CSensorFinder()
{
    if( iMagneticNorthSensor )
    {
        iMagneticNorthSensor->StopDataListening();
        iMagneticNorthSensor->CloseChannel();
        delete iMagneticNorthSensor, iMagneticNorthSensor = NULL;
    }
}

void CSensorFinder::DataReceived( CSensrvChannel& aChannel, TInt /*aCount*/, TInt /*aDataLost*/ )
{             
    TSensrvChannelInfo channelinfo = aChannel.GetChannelInfo();
    if( channelinfo.iChannelType == KSensrvChannelTypeIdMagneticNorthData )
    { 			
        TSensrvMagneticNorthData magNorthData;
        TPckg<TSensrvMagneticNorthData>  magNorthPackage(magNorthData);    		    		
        aChannel.GetData(magNorthPackage);    		
        iMagnetometerAngleFromNorth = magNorthData.iAngleFromMagneticNorth;
        TSensrvProperty calibration;
        aChannel.GetPropertyL(KSensrvPropCalibrationLevel,0,calibration);
        calibration.GetValue(iMagnetometerCalibrationLevel);     		     		     		
        if( iMagnetometerCalibrationLevel > 0 )
        {
            TRAP_IGNORE( iDataObserver.DataReceivedL( iMagnetometerAngleFromNorth, iMagnetometerCalibrationLevel ) );					
        }    			 
    }     
}

void CSensorFinder::DataError( CSensrvChannel& /*aChannel*/, TSensrvErrorSeverity /*aError*/ )
{
}

void CSensorFinder::GetDataListenerInterfaceL( TUid /*aInterfaceUid*/, TAny*& aInterface )
{
    aInterface = NULL;
}
